<template>
  <div class="article-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <h2>标签管理</h2>
          <el-button type="primary" @click="handleAdd" :icon="Plus">新增标签</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="标签名称" class="form-item">
            <el-input v-model="searchForm.name" placeholder="请输入标签标题"></el-input>
          </el-form-item>
          <el-form-item class="form-item">
            <el-button type="primary" @click="onSearch" :icon="Search">搜索</el-button>
            <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格区域 -->
      <div class="table-area">
        <el-table :data="tagList" style="width: 100%" @selection-change="handleSelectionChange" :stripe="true" :border="true">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="name" label="标签标题" min-width="180">
            <template #default="scope">
              <el-link type="primary" @click="viewArticle(scope.row)">{{ scope.row.name }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" width="180">
            <template #default="scope">
              {{  scope.row.description }}
            </template>
          </el-table-column>
          <el-table-column prop="tagList" label="颜色" width="180">
            <template #default="scope">
              <el-color-picker v-model="scope.row.color" disabled size="large"></el-color-picker>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleEdit(scope.row)" :icon="Edit">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)" :icon="Delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-area">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tagTotal">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑标签对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" destroy-on-close>
      <el-form :model="tagForm" label-width="80px" class="article-form">
        <el-form-item label="标签名">
          <el-input v-model="tagForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="tagForm.description"></el-input>
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="tagForm.color" size="large"></el-color-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitArticle">发布</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus, Delete, Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { toast } from '@/composables/util.js'
import {selectAllTag, selectByTagId ,deleteByTagId ,addTag ,updateTag } from '@/api/back/tag.js'
import store from "@/store"


// 搜索表单数据
const searchForm = reactive({
  name: ''
})

// 标签列表数据
const tagList = ref([
  // { id: 1, name: 'Vue3', description: '321321' },
  // { id: 2, name: 'React', description: '2342'},
  // ... 更多标签数据
])

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(5)
const tagTotal = ref(100)


// 选中的标签
const selectedArticles = ref([])

// 对话框相关数据
const dialogVisible = ref(false)
const dialogTitle = ref('新增标签')
const tagForm = reactive({
  id: null,
  name: '',
  description: '',
  color: ''
})

onMounted(async () => {
  InitDate()
})


//初始化数据
const InitDate = async () =>{
  await selectAllTag({pageNum: currentPage.value,pageSize: pageSize.value}).then((res) => {
    tagList.value=res.data.data.list
    tagTotal.value = res.data.data.total
  })
}


// 搜索方法
const onSearch = () => {
  console.log('搜索条件：', searchForm)
  selectAllTag({pageNum: currentPage.value,pageSize: pageSize.value, name: searchForm.name}).then(res => {
    tagList.value=res.data.data.list
    tagTotal.value = res.data.data.total
  })
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = Array.isArray(searchForm[key]) ? [] : ''
  })
}

// 新增标签
const handleAdd = () => {
  dialogTitle.value = '新增标签'
  Object.keys(tagForm).forEach(key => {
    tagForm[key] = Array.isArray(tagForm[key]) ? [] : ''
  })
  dialogVisible.value = true
}

// 编辑标签
const handleEdit = (row) => {
  dialogTitle.value = '编辑标签'

  Object.assign(tagForm, row)
  console.log("编辑行",tagForm)
  dialogVisible.value = true
}

// 删除标签
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这篇标签吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteByTagId(row.id).then(res=>{
      toast("删除成功!","success")
      InitDate()
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

// 查看标签
const viewArticle = (row) => {
  console.log('查看标签：', row)
  // 这里应该跳转到标签详情页或打开预览对话框
}

// 提交标签
const submitArticle = () => {
  console.log('提交标签：', tagForm)
  tagForm.userId = store.state.userInfo.id
  if(tagForm.id){
    updateTag(tagForm).then(res => {
      if(res.data.code === '200'){
        toast( '标签更新成功',"success")
        InitDate()
      }
    })
  }else{
    console.log("我进入了新增:" ,tagForm)
    addTag(tagForm).then(res => {
      if(res.data.code === '200'){
        toast( '标签发布成功',"success")
        InitDate()
      }
    })
  }

  dialogVisible.value = false
  InitDate()
}

// 表格选择变化
const handleSelectionChange = (val) => {
  selectedArticles.value = val
}

// 改变每页显示数量
const handleSizeChange = (val) => {
  pageSize.value = val
  // 这里应该重新加载标签列表
  selectAllTag({pageNum: currentPage.value,pageSize: pageSize.value, name: searchForm.name}).then(res => {
    tagList.value = res.data.data.list
    tagTotal.value = res.data.data.total
  })
}

// 改变页码
const handleCurrentChange = (val) => {
  currentPage.value = val
  selectAllTag({pageNum: currentPage.value,pageSize: pageSize.value, name: searchForm.name}).then(res => {
    tagList.value=res.data.data.list
    tagTotal.value = res.data.data.total
  })
}
</script>

<style scoped>
.article-management {
  padding: 20px;

  min-height: 100vh;
}

.main-card {
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h2 {
  margin: 0;
  color: #1f2f3d;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.form-item {
  margin-bottom: 10px;
  flex-grow: 1;
}

/* 确保最后一个表单项(按钮组)不会过度拉伸 */
.form-item:last-child {
  flex-grow: 0;
}

.table-area {
  margin-bottom: 20px;
}

.tag-item {
  margin-right: 5px;
  margin-bottom: 5px;
}

.pagination-area {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.article-form {
  max-width: 600px;
  margin: 0 auto;
}

.el-dialog__body {
  padding-top: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>